//
//  SportPlanViewController.m
//  SportsSocial
//
//  Created by yull on 14/10/29.
//  Copyright (c) 2014年 yull. All rights reserved.
//

#import "SportPlanViewController.h"
#import "YCalendarView.h"
#import "PlanSelectPanelView.h"
#import "UIView+Frame.h"
#import "PlanDetailViewController.h"
#import "PlanDao.h"

@interface SportPlanViewController () <YCalendarViewDelegate,PlanSelectPanelViewDelegate>

@property (nonatomic, strong) UIScrollView *contentScrollView;
@property (nonatomic, strong) YCalendarView *calendarView;
@property (nonatomic, strong) PlanSelectPanelView *selectPanelView;

@property (nonatomic, strong) NSArray *iconArray;
@property (nonatomic, strong) NSArray *selectIconArray;
@property (nonatomic, strong) NSArray *titleArray;
@property (nonatomic, strong) NSArray *unFinishedIconArray;
@property (nonatomic, strong) NSMutableArray *planArray;
@property (nonatomic, strong) NSMutableDictionary *planDict;
@end

@implementation SportPlanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self addCommonBackButton];
    self.navigationItem.title = @"我的运动计划";
    
    CGRect rect = CGRectMake(0, 0, self.view.width, self.view.height);
    self.contentScrollView = [[UIScrollView alloc] initWithFrame:rect];
    [self.view addSubview:self.contentScrollView];
    
    self.calendarView = [[YCalendarView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.frame), 0)];
    self.calendarView.delegate = self;
    [self.contentScrollView addSubview:self.calendarView];
    
    self.selectPanelView = [[PlanSelectPanelView alloc] initWithFrame:CGRectMake(0, self.calendarView.bottom + 10, CGRectGetWidth(self.view.frame), 0)];
    
    self.selectPanelView.delegate = self;
    [self.contentScrollView addSubview:self.selectPanelView];
    
    [self initSelectItem];
    
    UILabel *tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, self.calendarView.bottom - 10, self.view.width, 20)];
    tipLabel.backgroundColor = [UIColor clearColor];
    tipLabel.textAlignment = NSTextAlignmentCenter;
    tipLabel.textColor = [UIColor lightGrayColor];
    tipLabel.font = [UIFont systemFontOfSize:14];
    tipLabel.text = @"操作提示：长按并拖拽图标到日历上";
    [self.contentScrollView addSubview:tipLabel];
    
    self.contentScrollView.contentSize = CGSizeMake(self.view.width, self.selectPanelView.bottom + Navibar_Height);
    
    [self loadDataFromDB];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(planInfoStatusChange:) name:@"PlanInfoStatusChange" object:nil];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)initSelectItem
{
    self.iconArray = @[@"basketball_icon_normal",@"football_icon_normal",@"running_icon_normal",@"swimming_icon_normal",@"billiards_icon_normal",@"tennis_icon_normal",@"table_icon_normal"];
    self.selectIconArray = @[@"basketball_icon_pressed",@"football_icon_pressed",@"running_icon_pressed",@"swimming_icon_pressed",@"billiards_icon_pressed",@"tennis_icon_pressed",@"table_icon_pressed"];
    self.titleArray = @[@"篮球",@"足球",@"跑步",@"游泳",@"台球",@"网球",@"乒乓球"];
    
    self.unFinishedIconArray = @[@"basketball_icon_disable",@"football_icon_disable",@"running_icon_disable",@"swimming_icon_disable",@"billiards_icon_disable",@"tennis_icon_disable",@"table_icon_disable"];
    
    self.selectPanelView.imageArray = self.iconArray;
    self.selectPanelView.selectImageArray = self.selectIconArray;
    [self.selectPanelView reloadData];
}

#pragma mark - YCalendarViewDelegate
- (void)onClickPreButton
{
    [self loadDataFromDB];
}

- (void)onClickNextButton
{
    [self loadDataFromDB];
}

- (void)calendarViewChangeHeight:(CGFloat)height
{
    [UIView animateWithDuration:0.3f animations:^{
        self.calendarView.height = height;
        self.selectPanelView.top = self.calendarView.bottom + 10;
    } completion:^(BOOL finished) {
        self.contentScrollView.contentSize = CGSizeMake(self.view.width, self.selectPanelView.bottom + Navibar_Height);
    }];
}

- (void)didSelectMonth:(NSInteger)month day:(NSInteger)day
{
    NSString *key = [[NSString alloc] initWithFormat:@"%d",day];
    NSArray *planArray = [self.planDict objectForKey:key];
    if (planArray.count > 0) {
        PlanDetailViewController *planDetailVC = [[PlanDetailViewController alloc] init];
        planDetailVC.planArray = [NSMutableArray arrayWithArray:planArray];
        planDetailVC.navigationItem.title = [[NSString alloc] initWithFormat:@"%d月%d日",month,day];
        planDetailVC.day = day;
        planDetailVC.month = month;
        planDetailVC.year = self.calendarView.currentYear;
        
        @weakify(self);
        planDetailVC.deletePlanInfo = ^(PlanInfo *planInfo) {
            @strongify(self);
            [self deletePlanInfo:planInfo];
        };
        
        planDetailVC.addPlanInfo = ^(PlanInfo *planInfo) {
            @strongify(self);
            [[PlanDao shareInstance] insertPlanInfo:planInfo];
            
            //NSString *key = [[NSString alloc] initWithFormat:@"%d",planInfo.day];
            //NSMutableArray *array = [self.planDict objectForKey:key];
            //[array addObject:planInfo];
            
            [self.calendarView.monthView insertPlanInfo:planInfo];
        };
        
        [self.navigationController pushViewController:planDetailVC animated:YES];
    }
}

- (void)insertFailed:(NSString *)errorMsg
{
    [self showText:errorMsg];
}

#pragma mark -
- (void)moveEndPoint:(CGPoint)point selectIndex:(NSInteger)index
{
    CGPoint convertPoint = [self.selectPanelView convertPoint:point toView:self.calendarView.monthView.dayCollectionView];
    
    if (CGRectContainsPoint(self.calendarView.monthView.dayCollectionView.frame, convertPoint)) {
        PlanInfo *planInfo = [[PlanInfo alloc] init];
        planInfo.icon = [self.iconArray objectAtIndex:index];
        planInfo.sport_name = [self.titleArray objectAtIndex:index];
        planInfo.year = self.calendarView.currentYear;
        planInfo.month = self.calendarView.currentMonth;

        BOOL success = [self.calendarView.monthView insertPlanInfo:planInfo atPoint:convertPoint];
        
        if (success) {
            [self uploadPlanInfo:planInfo];
        }
    }
}

- (void)uploadPlanInfo:(PlanInfo *)planInfo
{
    [self savePlanInfo:planInfo];
}

- (void)savePlanInfo:(PlanInfo *)planInfo
{
    BOOL ret = [[PlanDao shareInstance] insertPlanInfo:planInfo];
    if (ret) {
        NSLog(@"运动计划保存数据库成功!");
    }else {
        NSLog(@"运动计划保存数据库失败!");
    }
}

- (void)loadDataFromDB
{
    if (!self.planArray) {
        self.planArray = [NSMutableArray array];
    }else {
        [self.planArray removeAllObjects];
    }
    
    [self.planArray addObjectsFromArray:[[PlanDao shareInstance] selectInfoWithYear:self.calendarView.currentYear Month:self.calendarView.currentMonth]];
    
    [self handlePlanInfo];
}

- (void)handlePlanInfo
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    
    for (NSInteger i=1;i<=self.calendarView.monthView.dayCount;i++) {
        NSMutableArray *array = [NSMutableArray array];
        NSString *key = [[NSString alloc] initWithFormat:@"%d",i];
        [dict setObject:array forKey:key];
    }
    
    for (PlanInfo *planInfo in self.planArray) {
        NSString *day = [[NSString alloc] initWithFormat:@"%d",planInfo.day];
        
        NSMutableArray *dayArray = [dict objectForKey:day];
        [dayArray addObject:planInfo];
    }
    
    self.calendarView.monthView.planDict = dict;
    [self.calendarView.monthView reloadData];
    
    self.planDict = dict;
}

- (void)deletePlanInfo:(PlanInfo *)planInfo
{
    NSString *dayStr = [[NSString alloc] initWithFormat:@"%d",planInfo.day];
    NSArray *array = [self.planDict objectForKey:dayStr];
    NSMutableArray *mutableArray = [NSMutableArray arrayWithArray:array];
    for (NSInteger i=0;i<array.count;i++) {
        PlanInfo *info = [array objectAtIndex:i];
        if ([info.sport_name isEqualToString:planInfo.sport_name]) {
            [mutableArray removeObjectAtIndex:i];
            [self.planDict setObject:mutableArray forKey:dayStr];
            self.calendarView.monthView.planDict = self.planDict;
            [self.calendarView.monthView reloadData];
            break;
        }
    }
}

- (void)planInfoStatusChange:(NSNotification *)notification
{
    [self.calendarView.monthView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
